package com.mh.task;

import com.mh.dao.GroupInfoDao;
import com.mh.dao.GroupUserDao;
import com.mh.dao.UserInfoDao;
import com.mh.pojo.GroupInfo;
import com.mh.pojo.GroupUser;
import com.mh.pojo.UserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Date:2024/9/8
 * author:zmh
 * description: 初始化所有接收者对象信息到Redis中
 **/

@Service
@RequiredArgsConstructor
@Slf4j
public class TaskOfInitReceiver {
    // Redis<'receiver-info', Map<接收者ID，接收者名称>>
    @Resource
    private RedisTemplate<String, Map<String,String>> redisTemplate;

    private final UserInfoDao userInfoDao;

    private final GroupInfoDao groupInfoDao;

    /**
     * 加载所有群组，用户的id和名称到Redis中。
     * 供前端主页根据接收者ID获取聊天对象的名称
     */
    @PostConstruct
    public void loadDataToRedis() {
        log.info(">>>>初始化接收者信息>>>>");
        HashMap<String, String> receiverInfo = new HashMap<>();
        // 查询出所有用户 和 群组
        for (UserInfo userInfo : userInfoDao.selectList(null)) {
            receiverInfo.put(userInfo.getUserId(),userInfo.getName());
        }

        for (GroupInfo groupInfo : groupInfoDao.selectList(null)) {
            receiverInfo.put(groupInfo.getGroupId(), groupInfo.getGroupName());
        }

        redisTemplate.opsForValue().set("receiver-info", receiverInfo);
        log.info("++++接收者信息初始化完成++++");
    }

    /**
     * 从Redis中获取接收者名称
     * @param ids   查询的收者ID
     * @return ·
     */
    public Map<String, String> getReceiverNames(List<String> ids){
        HashMap<String, String> resultMap = new HashMap<>();
        // 取出Redis中存入的所有接收者信息
        Map<String, String> receiverInfo = redisTemplate.opsForValue().get("receiver-info");
        // 遍历接收者信息Map，根据id选出匹配的接收者信息
        for (String id : ids) {
            // 据接收者ID，获取出接收者名称
            String receiverName = receiverInfo.get(id);
            resultMap.put(id, receiverName);
        }
        // 返回结果
        return resultMap;
    }
}
